﻿using RockHopper.TrainingCalculator.WinRT.ViewModel;
using RockHopper.Common.Events;
using RockHopper.Common.ViewModel;
using Windows.UI.Notifications;

namespace RockHopper.TrainingCalculator.WinRT
{
    public sealed partial class MainPage
    {
        private readonly TileUpdater updater;

        public MainPage()
        {
            InitializeComponent();
            updater = TileUpdateManager.CreateTileUpdaterForApplication();
            var model = (MainViewModel)Global.Container.Resolve<ViewModelBase>(typeof(MainViewModel).Name);
            DataContext = model;
            UpdateTile(model);
            DomainEvents.VdotChanged += (s, e) => UpdateTile(model);
            DomainEvents.PaceUnitsChanged += (s, e) => UpdateTile(model);
        }

        private void UpdateTile(MainViewModel model)
        {
            updater.Clear();
            updater.EnableNotificationQueue(true);

            AppendTileNotification("VDOT:", model.VdotTile.LiveTileInfo);
            AppendTileNotification("Easy:", model.EasyTile.LiveTileInfo);
            AppendTileNotification("Marathon:", model.MarathonTile.LiveTileInfo);
            AppendTileNotification("Threshold:", model.ThresholdTile.LiveTileInfo);
            AppendTileNotification("Intervals:", model.IntervalTile.LiveTileInfo);
            AppendTileNotification("Repetitions:", model.RepetitionTile.LiveTileInfo);
        }

        private void AppendTileNotification(string title, string info)
        {
            var tile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareText03);
            tile.GetElementsByTagName("text")[0].InnerText = title;
            tile.GetElementsByTagName("text")[1].InnerText = info;
            updater.Update(new TileNotification(tile));
            tile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideBlockAndText01);
            tile.GetElementsByTagName("text")[0].InnerText = title;
            tile.GetElementsByTagName("text")[1].InnerText = info;
            updater.Update(new TileNotification(tile));
        }
    }
}
